package com.itheima.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author weizhongli
 * @Date 2020/4/22
 * @Version v1.0
 * @Description
 **/
@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/findAll")
    public List<User> findAll() {
        return userService.findAll();
    }

    /*
     * 增加缓冲请求查询所有用户
     * */
    @GetMapping("/findAllCache")
    public String findAllCache() throws JsonProcessingException {
        //1.查询redis缓存
        //2.存在返回
        //3.不存在-MySQL数据库查找-转为json存入redis-返回

        String usersStr = "";
        usersStr = (String) redisTemplate.boundValueOps("users").get();

        if(StringUtils.isEmpty(usersStr)){
            log.info("_________从mysql数据库查找_________");
            List<User> userList = userService.findAll();
            ObjectMapper objectMapper = new ObjectMapper();
            usersStr = objectMapper.writeValueAsString(userList);
            redisTemplate.boundValueOps("users").set(usersStr);
        }
        return usersStr;
    }
}
